package com.supeng.PMdepot.activity;

import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.InputType;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.supeng.PMdepot.ItemDecoration.SpaceItemDecoration;
import com.supeng.PMdepot.R;
import com.supeng.PMdepot.adapter.PanDianAdapter;
import com.supeng.PMdepot.base.BaseActivity;
import com.supeng.PMdepot.common.Constant;
import com.supeng.PMdepot.entity.PanDianInfo;
import com.supeng.PMdepot.entity.PanDianReq;
import com.supeng.PMdepot.entity.RukuBeen;
import com.supeng.PMdepot.entity.RukuInfo;
import com.supeng.PMdepot.entity.ServiceResult;
import com.supeng.PMdepot.entity.SuokuInfo;
import com.supeng.PMdepot.net.Api;
import com.supeng.PMdepot.net.NetUtils;
import com.supeng.PMdepot.util.KeyboardUtils;
import com.supeng.PMdepot.util.ToastUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class PanDianActivity extends BaseActivity {
    @BindView(R.id.et_kucun)
    EditText etKucun;
    public String kufang;
    public String chanpin;
    @BindView(R.id.rv_list)
    RecyclerView rvList;
    @BindView(R.id.tv_cwtm)
    TextView tvCwtm;
    @BindView(R.id.tv_cptm)
    TextView tvCptm;
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.title_bar)
    RelativeLayout titleBar;
    @BindView(R.id.vv_blue2)
    View vvBlue2;
    @BindView(R.id.tv_kucun)
    TextView tvKucun;
    @BindView(R.id.tv_shipan)
    TextView tvShipan;
    @BindView(R.id.vv_blue3)
    View vvBlue3;
    @BindView(R.id.pandian_btn)
    TextView pandianBtn;
    @BindView(R.id.root_layout)
    LinearLayout rootLayout;
    @BindView(R.id.tv_quyu)
    TextView tvQuyu;
    @BindView(R.id.tv_quyucangwei)
    TextView tvQuyucangwei;
    @BindView(R.id.btn_quxiaopandian)
    Button btnQuxiaopandian;
    @BindView(R.id.btn_changcangwei)
    Button btnChangcangwei;
    private PanDianAdapter homeAdapter;
    private  List<SuokuInfo.InfoBean.CangweiBean> cangweiBeanList;
    private List<RukuBeen> tiaomaBeanList;
    private String pandiandanhao="";
    private boolean hasChangeCangwei=false;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //弹出键盘滚动问题
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        setContentView(R.layout.activity_pandian);
        unbinder = ButterKnife.bind(this);
        initView();
        initData();
        initAdapter();
    }

    private void initData() {

        etKucun.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {

                if (actionId == 0 || actionId == 6) {
                    if (event == null) {
                        if (actionOk(v)) return true;
                    } else {
                        switch (event.getAction()) {
                            case KeyEvent.ACTION_UP:
                                if (actionOk(v)) return true;
                        }
                    }
                }
                return true;

            }
        });


    }

    private boolean actionOk(TextView v) {
        String search = v.getText().toString();
        etKucun.setText("");
        if (TextUtils.isEmpty(search)) {
            ToastUtils.show("无效二维码");
            return true;
        }

        //库房二维码
        if (search.indexOf(Constant.DAKuFangkey) == 0) {
            if (!TextUtils.isEmpty(kufang)) {
                etKucun.setText("");
                ToastUtils.show("请等待盘点完成才可以进行下一条码扫描");
                return true;
            }
            clear();
            kufang = search.substring(1,search.length());
            tvQuyu.setText(kufang);
            dogetKufangByServer();
        } else {
            if (TextUtils.isEmpty(kufang)) {
                ToastUtils.show("请先扫描区域条码");
                return true;
            }
            if(hasChangeCangwei){
                if (search.indexOf(Constant.KuFangkey) == 0) {
                    String cangwei=search.substring(1,search.length());
                    boolean isIncangweiList=false;
                    String cangkubiaohao="";
                    for(SuokuInfo.InfoBean.CangweiBean cangweiBean:cangweiBeanList){
                        if(cangwei.equals(cangweiBean.getCangwei())){
                            cangkubiaohao=cangweiBean.getCangkubianhao();
                            isIncangweiList=true;
                        }
                    }
                    if(isIncangweiList) {
                        if(TextUtils.isEmpty(homeAdapter.getData().get(0).getCangwei())){
                            homeAdapter.getData().get(0).setCangwei(cangwei);
                            homeAdapter.getData().get(0).setCangkubianhao(cangkubiaohao);
                        }else {
                            homeAdapter.getData().get(0).setNewCangwei(cangwei);
                        }
                        tvCwtm.setText(cangwei);
                        hasChangeCangwei = false;
                        homeAdapter.notifyItemChanged(0);
                        ToastUtils.show("更改仓位成功");
                    }else{
                        ToastUtils.show("只能更改区域内的仓位");
                    }
                    return  true;
                }else{
                    ToastUtils.show("更改仓位中请扫描仓库条码");
                    return true;
                }
            }
            if (search.indexOf(Constant.ChanPinKey) == 0) {
                chanpin = search;
                tvCptm.setText(search);
            } else {
                ToastUtils.show("无效二维码");
                return true;
            }
        }

        //KeyboardUtils.hideSoftInput(v, getActivity());
        if (!TextUtils.isEmpty(chanpin) && !TextUtils.isEmpty(kufang)) {
            doAddServer(chanpin);
        }
        return false;
    }
    private void clearKuFang(){
        kufang="";
        tvQuyu.setText("");
    }
    private void dogetKufangByServer() {
      Api.suoku(getActivity(), kufang, true, "", new NetUtils.NetCallBack<ServiceResult>() {
          @Override
          public void success(ServiceResult rspData) {
                if(rspData.getRecode()==1){
                    SuokuInfo suokuInfo= (SuokuInfo) rspData;
                    cangweiBeanList=suokuInfo.getInfo().getCangwei();
                    tiaomaBeanList=suokuInfo.getInfo().getTiaoma();
                    pandiandanhao=suokuInfo.getInfo().getPandian();
                    if(tiaomaBeanList!=null&&tiaomaBeanList.size()>0) {
                        tvKucun.setText(tiaomaBeanList.size()+"");
                    }else{
                        tvKucun.setText("0");
                    }
                    tvShipan.setText("0");
                    String cangweis="";
                    for(SuokuInfo.InfoBean.CangweiBean cangweiBean:cangweiBeanList){
                        cangweis=cangweis+cangweiBean.getCangwei()+",";
                    }
                    cangweis=cangweis.substring(0,cangweis.length()-1);
                    tvQuyucangwei.setText(cangweis);
                }else{
                    ToastUtils.show("该区域没有仓位请检查条码");
                    clearKuFang();
                }
          }

          @Override
          public void failed(String msg) {
              ToastUtils.show(msg);
              clearKuFang();
          }

          @Override
          public void onUsedCache(String msg) {

          }
      },SuokuInfo.class);

    }

    private void doAddServer(final String mchanpin) {
        tvCptm.setText(mchanpin);
        Api.yksearch(getActivity(), mchanpin, new NetUtils.NetCallBack<ServiceResult>() {
            @Override
            public void success(ServiceResult rspData) {
                RukuInfo rukuInfo= (RukuInfo) rspData;
                RukuBeen rukuBeen=rukuInfo.getInfo();
                if(rukuBeen!=null){
                    List<RukuBeen> rukuBeenList = homeAdapter.getData();
                    for (RukuBeen rukuBeent : rukuBeenList) {
                        if (rukuBeent.getCptiaoma().equals(mchanpin)) {
                            tvCptm.setText("");
                            //todo server OK
                            chanpin = "";
                            ToastUtils.show("条码已录入");
                            return;
                        }
                    }
                    for(RukuBeen  rukuBeent:tiaomaBeanList){
                        if(rukuBeent.getCptiaoma().equals(rukuBeen.getCptiaoma())){
                            rukuBeen.setShow(true);
                            break;
                        }
                    }
                    tvCwtm.setText(rukuBeen.getCangwei());
                    homeAdapter.addData(0, rukuBeen);
                    homeAdapter.notifyItemChanged(0);
                    rvList.smoothScrollToPosition(0);
                    if(!"IN".equals(rukuBeen.getZhuangtai())){
                        tvCwtm.setText("");
                        hasChangeCangwei=true;
                    }else{
                        boolean isInQuyu=false;
                        for(SuokuInfo.InfoBean.CangweiBean cangweiBean:cangweiBeanList){
                            if(rukuBeen.getCangwei().equals(cangweiBean.getCangwei())){
                                isInQuyu=true;
                                break;
                            }
                        }
                        if(!isInQuyu){
                             new AlertDialog.Builder(getActivity()).setCancelable(false)
                                    .setTitle("条码仓位不在区域内，是否盘点此条码？")
                                    .setNegativeButton("盘点", new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            tvCwtm.setText("");
                                            hasChangeCangwei=true;
                                            dialog.dismiss();
                                        }
                                    })
                                    .setPositiveButton("否", new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            tvCwtm.setText("");
                                            tvCptm.setText("");
                                            chanpin="";
                                            homeAdapter.remove(0);
                                            dialog.dismiss();
                                        }
                                    })
                                    .show();
                        }

                    }
                    setLyCount();
                }else{
                    tvCptm.setText("");
                    chanpin = "";
                    ToastUtils.show("产品条码不存在");
                }
            }

            @Override
            public void failed(String msg) {
                ToastUtils.show(msg);
                tvCptm.setText("");
                chanpin = "";
            }

            @Override
            public void onUsedCache(String msg) {

            }
        },RukuInfo.class);
    }

    private void initAdapter() {

        rvList.setLayoutManager(new LinearLayoutManager(getActivity()));
        rvList.addItemDecoration(new SpaceItemDecoration(getActivity()).setSpace(0.5f).setSpaceColor(getResources().getColor(R.color.item_press2)));
        homeAdapter = new PanDianAdapter();
        homeAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                switch (view.getId()) {
                    case R.id.tv_name:
                        break;
                }
            }
        });
        homeAdapter.setOnItemLongClickListener(new BaseQuickAdapter.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(BaseQuickAdapter adapter, View view, final int position) {
                final RukuBeen rukuBeen = (RukuBeen) adapter.getData().get(position);
                AlertDialog dialog = new AlertDialog.Builder(getActivity()).setCancelable(false)
                        .setTitle("是否删除产品编号" + rukuBeen.getCptiaoma() + "这条记录")
                        .setNegativeButton("是", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                doDelete(position);
                                dialog.dismiss();
                            }
                        })
                        .setPositiveButton("否", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        })
                        .show();
                return false;
            }
        });
        homeAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, final int position) {

            }
        });
        homeAdapter.setEmptyView(R.layout.loading_view, (ViewGroup) rvList.getParent());
        rvList.setAdapter(homeAdapter);

        homeAdapter.setNewData(null);
    }

    private void doDelete( int postion) {
        if(postion==0){
            hasChangeCangwei=false;
            chanpin="";
            tvCwtm.setText("");
            tvCptm.setText("");
        }
        homeAdapter.remove(postion);
            setLyCount();
    }

    private void setLyCount() {
        tvShipan.setText(homeAdapter.getData().size() + "");
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if(!TextUtils.isEmpty(pandiandanhao)) {
                new AlertDialog.Builder(getActivity()).setCancelable(false)
                        .setTitle("是否取消盘点？")
                        .setNegativeButton("确认取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                KeyboardUtils.hideSoftInput(iv_back, getActivity());
                                qxsuoKu(true);
                            }
                        })
                        .setPositiveButton("继续盘点", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        })
                        .show();
                return true;
            }else{
                KeyboardUtils.hideSoftInput(iv_back, getActivity());
                finish();
            }

        }

        return super.onKeyDown(keyCode, event);
    }
    public void clear(){
        cangweiBeanList=null;
        tiaomaBeanList=null;
        homeAdapter.setNewData(null);
        tvCwtm.setText("");
        tvQuyu.setText("");
        tvCptm.setText("");
        tvQuyucangwei.setText("");
        tvShipan.setText("0");
        tvKucun.setText("0");
        chanpin="";
        kufang="";
        pandiandanhao="";
    }

    public void qxsuoKu(final boolean isFinish){
        Api.suoku(getActivity(), kufang, false, pandiandanhao, new NetUtils.NetCallBack<ServiceResult>() {
            @Override
            public void success(ServiceResult rspData) {
                ToastUtils.show("区域"+kufang+"已取消盘点");
                clear();
                if(isFinish) {
                    finish();
                }
            }

            @Override
            public void failed(String msg) {

            }

            @Override
            public void onUsedCache(String msg) {

            }
        },ServiceResult.class);
    }
    private void initView() {
        iv_back = (ImageView) findViewById(R.id.iv_back);
        if (iv_back != null) {
            iv_back.setOnClickListener(new View.OnClickListener() {
                public final void onClick(View v) {
                    if(!TextUtils.isEmpty(pandiandanhao)) {
                        new AlertDialog.Builder(getActivity()).setCancelable(false)
                                .setTitle("是否取消盘点？")
                                .setNegativeButton("确认取消", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        KeyboardUtils.hideSoftInput(iv_back, getActivity());
                                        qxsuoKu(true);
                                    }
                                })
                                .setPositiveButton("继续盘点", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        dialog.dismiss();
                                    }
                                })
                                .show();
                    }else{
                        finish();
                    }
                }
            });
        }
        btnQuxiaopandian.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(!TextUtils.isEmpty(pandiandanhao)){
                    qxsuoKu(false);
                }else{
                    ToastUtils.show("当前没有库锁定");
                }

            }
        });
        btnChangcangwei.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!TextUtils.isEmpty(pandiandanhao)&&homeAdapter.getData().size()>0) {
                    new AlertDialog.Builder(getActivity()).setCancelable(false)
                            .setTitle("是否确认更改仓库？")
                            .setNegativeButton("更改", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    hasChangeCangwei = true;
                                    dialog.dismiss();
                                }
                            })
                            .setPositiveButton("否", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                }
                            })
                            .show();
                }else{
                    ToastUtils.show("当前没有数据无法更改仓库");
                }
            }
        });
        etKucun.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                etKucun.setInputType(InputType.TYPE_CLASS_TEXT);
                return false;
            }
        });
        etKucun.setInputType(InputType.TYPE_NULL);
    }

    private AlertDialog dialog;

    @OnClick(R.id.pandian_btn)
    public void onClick() {
        if(TextUtils.isEmpty(pandiandanhao)){
            ToastUtils.show("请先扫码区域条码");
            return;
        }
        if(homeAdapter.getData().size()==0){
            ToastUtils.show("没有数据盘点");
            return;
        }
        if(hasChangeCangwei){
            ToastUtils.show("更改完仓位才能盘点");
            return;
        }
        //
        List<RukuBeen> rukuBeenst=homeAdapter.getData();
        boolean isyiyang=true;
        for(RukuBeen rukuBeen:rukuBeenst){
            if(!rukuBeen.isShow()){
                isyiyang=false;
            }
        }
        int count=0;
        if(tiaomaBeanList!=null&&tiaomaBeanList.size()>0){
            count=tiaomaBeanList.size();
        }
        if(rukuBeenst.size()!=count){
            isyiyang=false;
        }
        String str = "";
        if (!isyiyang) {
            str = "数据不一致";
        }

        if (dialog == null || !dialog.isShowing()) {
            if (TextUtils.isEmpty(str)) {
                dialog = new AlertDialog.Builder(getActivity()).setCancelable(false)
                        .setTitle("是否确认盘点？")
                        .setNegativeButton("盘点", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                doEnterByServer();
                                dialog.dismiss();
                            }
                        })
                        .setPositiveButton("否", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        })
                        .show();
            } else {
                dialog = new AlertDialog.Builder(getActivity())
                        .setCancelable(false)
                        .setTitle(str + "是否确认？")
                        .setNegativeButton("确认", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                                new AlertDialog.Builder(getActivity())
                                        .setTitle("是否确认盘点？")
                                        .setNegativeButton("确认", new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialog, int which) {
                                                doEnterByServer();
                                                dialog.dismiss();
                                            }
                                        }).setPositiveButton("否", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        dialog.dismiss();
                                    }
                                })
                                        .show();
                            }
                        })
                        .setPositiveButton("否", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        })
                        .show();
            }
        }
    }


    //确认盘点
    private void doEnterByServer() {

        List<RukuBeen> rukuBeenst=homeAdapter.getData();
        List<RukuBeen> rukuBeens=new ArrayList<>();
       rukuBeens.addAll(rukuBeenst);
        PanDianReq panDianReq=new PanDianReq();
        panDianReq.setQuyu(tvQuyu.getText().toString());
        panDianReq.setPandianbianhao(pandiandanhao);
        panDianReq.setRukuBeenList(rukuBeens);
        boolean notChange=true;
        if(tiaomaBeanList!=null&&tiaomaBeanList.size()>0) {
            //库存条码未扫到出库
            for (RukuBeen tiaomaBean : tiaomaBeanList) {
                boolean hastiaoma=false;
                for(RukuBeen rukuBeen:rukuBeens){
                    if(rukuBeen.getCptiaoma().equals(tiaomaBean.getCptiaoma())){
                        hastiaoma=true;
                        break;
                    }
                }
                if(hastiaoma==false){
                    tiaomaBean.setIsneedPanDian("OUT");
                    rukuBeens.add(tiaomaBean);
                    notChange=false;
                }
            }
            //库存条码sa出库
            for(RukuBeen rukuBeen:rukuBeens) {
                boolean hastiaoma=false;
                for (RukuBeen tiaomaBean : tiaomaBeanList) {
                    if(rukuBeen.getCptiaoma().equals(tiaomaBean.getCptiaoma())){
                        hastiaoma=true;
                        break;
                    }
                }
                if(hastiaoma==false){
                    rukuBeen.setIsneedPanDian("IN");
                    notChange=false;
                }
            }
        }else{

            for(RukuBeen rukuBeen:rukuBeens){
                rukuBeen.setIsneedPanDian("IN");
                notChange=false;
            }
        }
        for(RukuBeen rukuBeen:rukuBeens){
            if(!TextUtils.isEmpty(rukuBeen.getNewCangwei())){
                notChange=false;
            }
        }
        panDianReq.setHasChange(notChange);
        Api.pandian(getActivity(), panDianReq, new NetUtils.NetCallBack<ServiceResult>() {
            @Override
            public void success(ServiceResult rspData) {
                if(rspData.getRecode()==1){
                    clear();
                   ToastUtils.show("盘点成功");
                }else{
                    ToastUtils.show("部分盘点失败");
                }

            }

            @Override
            public void failed(String msg) {
                ToastUtils.show(msg);
            }

            @Override
            public void onUsedCache(String msg) {

            }
        },PanDianInfo.class);

    }
}
